package gui;
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import client.ClientConsole;

import logic.BorrowHistory;
import logic.Librarian;
import logic.Message;
import logic.Reader;

/**
 * Shows reader's borrow history, enables extending manually book return date
 */
public class ViewReaderForm extends JPanel implements ActionListener{

	private JTextField readerSearch,extendDateText;
	private JLabel userName,status,cellphone,email;
	/**  GUI Panel used for Design*/
	private JPanel mainPanel,searchPanel,centerPanel,bottomPanel,readerFormPanel,historyPanel,extendPanel;
	private JButton back, search,extendDateButton;
	private JLabel readerSearchLabel;
	private JLabel userNameLabel;
	private JLabel statusLabel; 
	private JLabel cellphoneLabel; 
	private JLabel emailLabel; 
	/** show feedback form the server*/
	private JLabel error,errorLabel;
	/** the index of the book to be extended*/
	private int extendBorrow;
	/** saves the properties of the GridBagLayout for*/
	GridBagConstraints gbc = new GridBagConstraints();
	/** message from server about reader's details*/
	Message msg;
	/** holds readers history*/
	Object[] o;
	
	/**
	 * Default constructor-Builds the view reader form
	 */
	public ViewReaderForm()
	{
		super();
		setSize(300, 300);
		mainPanel=new JPanel();
		mainPanel.setLayout(new BorderLayout());
		centerPanel=new JPanel();
		centerPanel.setLayout(new BoxLayout( centerPanel, BoxLayout.Y_AXIS ));
		readerSearch=new JTextField(20);
		readerSearchLabel=new JLabel("Reader id: ");
		search= new JButton("Search");
		search.addActionListener(this);
		searchPanel=new JPanel();
		searchPanel.add(readerSearchLabel);
		searchPanel.add(readerSearch);
		searchPanel.add(search);
		mainPanel.add(searchPanel,BorderLayout.NORTH);
		readerFormPanel=new JPanel();
		readerFormPanel.setLayout(new GridBagLayout());
		gbc.insets= new Insets(7,7,7,7);
		userNameLabel=new JLabel("UserName: ");
		gbc = new GridBagConstraints();
		gbc.gridx=0;
		gbc.gridy=0;
		readerFormPanel.add(userNameLabel,gbc);
		userName=new JLabel();
		gbc = new GridBagConstraints();
		gbc.gridx=1;
		gbc.gridy=0;
		readerFormPanel.add(userName,gbc);
		cellphoneLabel=new JLabel("Cellphone: ");
		gbc = new GridBagConstraints();
		gbc.gridx=2;
		gbc.gridy=0;
		readerFormPanel.add(cellphoneLabel,gbc);
		cellphone=new JLabel();
		gbc = new GridBagConstraints();
		gbc.gridx=3;
		gbc.gridy=0;
		readerFormPanel.add(cellphone,gbc);
		emailLabel=new JLabel("Email: ");
		gbc = new GridBagConstraints();
		gbc.gridx=0;
		gbc.gridy=1;
		readerFormPanel.add(emailLabel,gbc);
		email=new JLabel();
		gbc = new GridBagConstraints();
		gbc.gridx=1;
		gbc.gridy=1;
		readerFormPanel.add(email,gbc);
		statusLabel=new JLabel("Status: ");
		gbc = new GridBagConstraints();
		gbc.gridx=2;
		gbc.gridy=1;
		readerFormPanel.add(statusLabel,gbc);
		status=new JLabel();
		gbc = new GridBagConstraints();
		gbc.gridx=3;
		gbc.gridy=1;
		readerFormPanel.add(status,gbc);
		
		centerPanel.add(readerFormPanel);
		readerFormPanel.setVisible(false);
		historyPanel=new JPanel(new GridBagLayout());
		centerPanel.add(historyPanel);
		mainPanel.add(centerPanel,BorderLayout.CENTER);
		
		bottomPanel=new JPanel();
		back=new JButton("back");
		bottomPanel.add(back);
		back.addActionListener(this);
		error=new JLabel();
		error.setVisible(false);
		bottomPanel.add(error);
		mainPanel.add(bottomPanel,BorderLayout.SOUTH);
		add(mainPanel);
		
	}
	
	/**
	 * shows reader's history and enables manual extend of return book
	 * @param reader reader's id to be shown
	 */
	private void findHistory(int reader) {
		Reader r=new Reader(reader);
		msg=new Message ("Reader History",r);
		ClientConsole.HandleMessageFromGui(msg);
		msg=(Message)ClientConsole.client.getMessage();
		if (msg.getCommand().equals("History Found"))
			o=(Object[]) msg.getObjects();
		
		if (msg.getCommand().equals("History Found"))
		{
			int index=0;
			int i=1;
			JLabel borrowedBookLabel=new JLabel("Book Name");
			gbc = new GridBagConstraints();
			gbc.gridx=0;
			gbc.gridy=0;
			gbc.insets= new Insets(7,7,7,7);
			historyPanel.add(borrowedBookLabel,gbc);
			JLabel borrowDateLabel=new JLabel("Borrow Date");
			gbc = new GridBagConstraints();
			gbc.gridx=1;
			gbc.gridy=0;
			gbc.insets= new Insets(7,7,7,7);
			historyPanel.add(borrowDateLabel,gbc);
			JLabel returnDateLabel=new JLabel("Return Date");
			gbc = new GridBagConstraints();
			gbc.gridx=2;
			gbc.gridy=0;
			gbc.insets= new Insets(7,7,7,7);
			historyPanel.add(returnDateLabel,gbc);
			JLabel actualReturnDateLabel=new JLabel("Actual return Date");
			gbc = new GridBagConstraints();
			gbc.gridx=3;
			gbc.gridy=0;
			gbc.insets= new Insets(7,7,7,7);
			historyPanel.add(actualReturnDateLabel,gbc);
			
			String pattern="yyyy-MM-dd";
			SimpleDateFormat dateFormat=new SimpleDateFormat(pattern);
			//show all reader's history
			for (index=0;index<o.length;index++)
			{
				JLabel borrowedBook=new JLabel(String.valueOf(((BorrowHistory) o[index]).getCatalogNumber()));
				gbc = new GridBagConstraints();
				gbc.gridx=0;
				gbc.gridy=i;
				gbc.insets= new Insets(4,4,4,4);
				historyPanel.add(borrowedBook,gbc);
				JLabel borrowDate=new JLabel(dateFormat.format(((BorrowHistory) o[index]).getBorrowDate()));
				gbc = new GridBagConstraints();
				gbc.gridx=1;
				gbc.gridy=i;
				gbc.insets= new Insets(4,4,4,4);
				historyPanel.add(borrowDate,gbc);
				JLabel returnDate=new JLabel(dateFormat.format(((BorrowHistory) o[index]).getReturnDate()));
				gbc = new GridBagConstraints();
				gbc.gridx=2;
				gbc.gridy=i;
				gbc.insets= new Insets(4,4,4,4);
				historyPanel.add(returnDate,gbc);
				
				if (((BorrowHistory) o[index]).getActualReturnDate()!=null)
				{
					JLabel  actualReturnDate = new JLabel(dateFormat.format(((BorrowHistory) o[index]).getActualReturnDate()));
					gbc = new GridBagConstraints();
					gbc.gridx=3;
					gbc.gridy=i;
					gbc.insets= new Insets(4,4,4,4);
					historyPanel.add(actualReturnDate,gbc);
				}
				else
				{
					JLabel  actualReturnDate = new JLabel("");
					gbc = new GridBagConstraints();
					gbc.gridx=3;
					gbc.gridy=i;
					gbc.insets= new Insets(4,4,4,4);
					historyPanel.add(actualReturnDate,gbc);			
				}
				JButton  extendButton = new JButton("Extend Return");
				extendButton.setName(String.valueOf(index));
				gbc = new GridBagConstraints();
				gbc.gridx=4;
				gbc.gridy=i++;
				gbc.insets= new Insets(4,4,4,4);
				historyPanel.add(extendButton,gbc);
				extendButton.addActionListener(this);
			}
			extendPanel=new JPanel();
			gbc = new GridBagConstraints();
			gbc.gridx=0;
			gbc.gridy=i++;
			gbc.gridwidth=4;
			gbc.insets= new Insets(4,4,4,4);
			historyPanel.add(extendPanel,gbc);
			extendDateText = new JTextField(15);
			extendDateButton=new JButton("Extend");
			extendDateButton.addActionListener(this);
			extendPanel.add(extendDateText);
			extendPanel.add(extendDateButton);
			extendPanel.setVisible(false);
		}
		else
		{
			errorLabel=new JLabel();
			errorLabel.setText(msg.getCommand());
			historyPanel.add(errorLabel);
		}
		
	}
	@Override
	public void actionPerformed(ActionEvent ae) {
		if ( ae.getSource() == back )
		{
			this.setVisible(false);
			if (ClientConsole.reader instanceof LibraryManager)
				ClientConsole.aFrame.setContentPane(new LibraryManagerWindow());
			else if (ClientConsole.reader instanceof Librarian)
				ClientConsole.aFrame.setContentPane(new LibrarianWindow());
			
		}
		else if (ae.getSource() == search)
		{
			if (readerSearch.getText().isEmpty())
			{
				error.setVisible(true);
				error.setText("Please fiil all fields");
			}
			else
			{
				centerPanel.remove(historyPanel);
				validate();
				historyPanel= new JPanel(new GridBagLayout());
				centerPanel.add(historyPanel);
				
				Message msg=new Message ("GetReader",Integer.parseInt(readerSearch.getText()));
				Reader r;
				ClientConsole.HandleMessageFromGui(msg);
				msg=(Message)ClientConsole.client.getMessage();
				if (msg.getCommand().equals("The user exist"))
				{
					r=(Reader) msg.getObjects();
					userName.setText(r.getUsername());
					cellphone.setText(r.getCellphone());
					email.setText(r.getEmail());
					status.setText(r.getStatus());
					error.setVisible(false);
					readerFormPanel.setVisible(true);
					findHistory(Integer.parseInt(readerSearch.getText()));
				}
				else
				{
					userName.setText("");
					cellphone.setText("");
					email.setText("");
					status.setText("");
					readerFormPanel.setVisible(false);
					error.setVisible(true);
					error.setText(msg.getCommand());
					extendPanel.setVisible(false);
				}
			}
		}
		// extend the return date of a book
		else if (ae.getSource()==extendDateButton)
		{
			if (!extendDateText.getText().isEmpty())
			{
				SimpleDateFormat dateFormat=new SimpleDateFormat("dd/MM/yyyy");
				BorrowHistory bh;
				Reader r;
				Object[] exetndRequset=new Object[3];
				bh=(BorrowHistory) o[extendBorrow];
				try {
					bh.setReturnDate(new java.sql.Date (dateFormat.parse(extendDateText.getText()).getTime()));
				} catch (ParseException e) {
					error.setText("Incorrect date");
				}
				r=new Reader(Integer.parseInt(readerSearch.getText()));
				exetndRequset[0]=bh;
				exetndRequset[1]=r;
				exetndRequset[2]=(Librarian) ClientConsole.reader;
				msg=new Message ("LibrarianExtend",exetndRequset);
				ClientConsole.HandleMessageFromGui(msg);
				msg=(Message)ClientConsole.client.getMessage();
				if (msg.getCommand().equals("Return date extended"))
				{
					error.setVisible(true);
					error.setText(msg.getCommand());
				}
				else
				{
					error.setVisible(true);
					error.setText(msg.getCommand());
				}
			}
			else
			{
				error.setVisible(true);
				error.setText("Please fill all fields");
			}
		}
		//determine which book was selected
		else
		{
			int index=Integer.parseInt(((JButton)ae.getSource()).getName());
			extendBorrow=index;
			extendPanel.setVisible(true);
			System.out.print("index:"+((JButton)ae.getSource()).getName());
		}
	}
}
